import os
import base64
import hashlib
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest
from django import forms
from django.conf import settings
from blog.models import Article

# Create your views here.
class FileUploadForm(forms.Form):
    username = forms.CharField()
    headImg = forms.ImageField()


# 处理上传的文件
def handle_uploaded_file(request):
    # 通过Referer获取文章的id，其实这样感觉不太好
    imgDir = request.META['HTTP_REFERER'][
        request.META['HTTP_REFERER'].index('article/') + len('article/'):-1]

    # 判断是否存在对应id的文章
    if not Article.objects.filter(pk=imgDir):
        return HttpResponseBadRequest("Bad")

    title = Article.objects.get(pk=imgDir).title

    if request.method == 'POST':
        if request.FILES:
            ret = _handle_write_file(request.FILES['img'], imgDir, title)

            if ret:
                return HttpResponse(r"/media/{imgDir}/imgsUpload/{name}".format(imgDir=imgDir, name=request.FILES['img'].name))
            else:
                return HttpResponse("ErrorName")

        elif request.POST['base64Date']:
            # 根据图片的内容生成md5，用于后面的图片名字，主要是防止冲突
            imgData = base64.b64decode(
                request.POST['base64Date'][request.POST['base64Date'].find(',') + 1:])
            m2 = hashlib.md5()
            m2.update(imgData)

            # imgDir实际上是文章的id，这里使用id作为粘贴上传的文件夹
            imgName = m2.hexdigest()

            # 图片名字的存储方式为图片md5(文章的title)
            imgName = '{1}_{0}_'.format(title, imgName)
            _handle_write_base64_img(imgData, imgName, imgDir)

            # 返回图片的链接地址，这里主要是返回给thinker-md编辑器使用的
            return HttpResponse("/media/{imgDir}/imgsUpload/{name}.jpg".format(imgDir=imgDir, name=imgName))

    return HttpResponse("无图片上传")


# 这是用于直接粘贴图片的
def _handle_write_base64_img(base64Date, imgName, imgDir=None):
    # 如果有对应的id的话那么就上传到分类的相关id的文件夹，没有的话就上传到ajaxUpload（这里主要是之前)
    if imgDir:
        uploadImg = r'{0}/{1}/{2}'.format(
            settings.MEDIA_ROOT, imgDir, "imgsUpload")
    else:
        uploadImg = r'{0}/{1}'.format(settings.MEDIA_ROOT,  "ajaxUpload")
    _uplodaImgFile(uploadImg)
    img = "{imgPath}/{imgName}.jpg".format(imgPath=uploadImg, imgName=imgName)
    with open(img, "wb") as f:
        f.write(base64Date)


# 这是直接上传本地图像的
def _handle_write_file(f, imgDir=None, title=None):
    if imgDir:
        uploadImg = r'{0}/{1}/{2}'.format(
            settings.MEDIA_ROOT, imgDir, "imgsUpload")
    else:
        uploadImg = r'{0}/{1}'.format(settings.MEDIA_ROOT,  "ajaxUpload")

    _uplodaImgFile(uploadImg)
    # 如果上传的图像文件名字已经存在 返回错误
    for r, d, fileName in os.walk(uploadImg):
        for name in fileName:
            if name == f.name:
                return False

    img = "{0}/{1}_{2}_".format(uploadImg, f.name,
                                title) if title else "{0}/{1}".format(uploadImg, f.name)

    with open(img, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

    return True


# 创建存放上传图像的文件夹
def _uplodaImgFile(filename):
    if not os.path.exists(filename):
        os.makedirs(filename)


# def showimg(request):
#     return render(request, r'blog/testimg.html')
